/*
 * Copyright (c) 2007-2021 西安交通信息投资营运有限公司 版权所有
 */

package com.xci.xajtfb.bus.service;

import com.github.lvyanyang.core.XCI;
import com.xci.xajtfb.bus._core.IntelligentAdjustableBaseService;
import com.xci.xajtfb.bus.dao.BusIntelligentAdjustableDao;
import com.xci.xajtfb.bus.entity.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 服务
 * @author 马星俊 maxingjun@xci96716.com
 * @since 2021-03-08 16:31:56
 */
@Service
public class BusIntelligentAdjustableService extends IntelligentAdjustableBaseService {
    /** 数据层对象 */
    @Resource private BusIntelligentAdjustableDao busIntelligentAdjustableDao;
    /** 线路服务 */
    @Resource private TbBusLineService tbBusLineService;
    /** 站点服务 */
    @Resource private TbBusStationService tbBusStationService;

    /**
     * 通过线路标识查询实时公交信息
     * @param routeId 线路Id
     * @return 返回实体
     */
    public RealBus getRealBusLine(@NotNull(message = "请指定线路Id") String routeId) {
        //查询实时公交
        TbBusLine busLine = tbBusLineService.selectByRouteId(routeId);
        LineInfo line = getLineInfo(busLine);
        line.setUp(getSegmentInfoList(busLine,routeId,1));
        line.setDown(getSegmentInfoList(busLine,routeId,2));

        RealBus realBusModel = new RealBus();
        realBusModel.setMessage("success");
        if (XCI.isEmpty(line.getCompanyId())) //企业应用
        {
            getRealBusLineCore(realBusModel, line);
        }
        else //智能调度
        {
            //开始从智能调度获取实时数据;
            getRealBusLineCoreBySch(realBusModel, line);
        }
        if (realBusModel.getUp() == null || realBusModel.getUp().size() == 0)
        {
            getRealBusLineCore(realBusModel, line);
        }
        realBusModel.setLineId(busLine.getLineId());
        realBusModel.setLineSerial(busLine.getLineSerial());
        realBusModel.setTicketPrice(busLine.getTicketPrice());
        realBusModel.setFirstTime(busLine.getFirstTime());
        realBusModel.setLastTime(busLine.getLastTime());
        realBusModel.setFirstTimeD(busLine.getFirstTimeD());
        realBusModel.setLastTimeD(busLine.getLastTimeD());
        realBusModel.setIsSwipe(line.getIsSwipe());
        realBusModel.setTicketSystem(line.getTicketSystem());
        return realBusModel;
    }

    /**
     * 通过线路标识查询实时公交信息(智能调度)
     * @param model
     * @param line
     */
    private void getRealBusLineCoreBySch(RealBus model, LineInfo line)
    {
        RealBus bus = getLineRunNumsAvgInterval(line.getCompareLineId());
        model.setRunNums(bus.getRunNums());
        model.setAvgInterval(bus.getAvgInterval());
        List<RealBusStation> stationList = getRealBusUpDown(line.getCompareLineId());
        model.setUp(processBusCodes(stationList.stream().filter(p->p.getRunningType().equals("up")).collect(Collectors.toList()), line.getLineId(),1));
        model.setDown(processBusCodes(stationList.stream().filter(p->p.getRunningType().equals("dow")).collect(Collectors.toList()), line.getLineId(),2));
        model.setHasRealBus(model.getUp().size() > 0 && stationList.stream().mapToInt(p -> p.getBusCount()).sum()>0);
    }

    private List<RealBusStation> processBusCodes(List<RealBusStation> lists, String lineId, int direction)
    {
        for (RealBusStation item : lists)
        {
            item.setBusCodes(getProcessBusCodes(item.getBusCount()));
            item.setRunningType(lineId+"_"+direction);
        }
        return lists;
    }

    private String getProcessBusCodes(int count)
    {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < count; i++)
        {
            sb.append("1,1");
            if (i < count - 1)
            {
                sb.append("_");
            }
        }
        return sb.toString();
    }

    /**
     * 通过线路标识获取实时公交信息(企业应用)
     * @param model
     * @param line
     */
    private void getRealBusLineCore(RealBus model, LineInfo line)
    {
        model.setRunNums(0);
        model.setAvgInterval(0);
        //上行
        if (line.getUp()!=null)
        {
            model.setUp(getRealBusStationModelList(line.getUp(), true));
        }
        //下行
        if (line.getDown()!=null)
        {
            model.setDown(getRealBusStationModelList(line.getDown(), false));
        }
    }

    private List<RealBusStation> getRealBusStationModelList(SegmentInfo model,boolean isUp){
        List<RealBusStation> result = new ArrayList<RealBusStation>();
        RealBusStation rbs ;
        for(int i=0;i<model.getStations().size();i++){
            rbs = new RealBusStation();
            rbs.setStationId(model.getStations().get(i).getStationId());
            rbs.setStationName(model.getStations().get(i).getStationName());
            rbs.setRunningType(model.getSegmentId());
            rbs.setOrderNumber(i+1);
//            rbs.setBusCodes();
//            rbs.setLeavebusCodes();
            result.add(rbs);
        }
        return result;
    }

    /**
     * 查询智能调的平均发车间隔、车辆数等
     * @param routeId 线路Id
     * @return 返回实体
     */
    private RealBus getLineRunNumsAvgInterval(String routeId) {
        return busIntelligentAdjustableDao.getLineRunNumsAvgInterval(routeId);
    }

    /**
     * 查询智能调的平均发车间隔、车辆数等
     * @param routeId 线路Id
     * @return 返回实体
     */
    private List<RealBusStation> getRealBusUpDown(String routeId) {
        return busIntelligentAdjustableDao.getRealBusUpDown(routeId);
    }

    private LineInfo getLineInfo(TbBusLine line){
        LineInfo entity = new LineInfo();
        entity.setLineId(line.getLineId());
        entity.setLineSerial(line.getLineSerial());
        entity.setCompanyId(line.getCompanyId());
        entity.setTicketSystem(line.getTicketSystem());
        entity.setIsSwipe(line.getIsSwipe());
        entity.setTicketPrice(line.getTicketPrice());
        entity.setCompareLineId(line.getCompareLineId());
        entity.setCompareLineSerial(line.getCompareLineSerial());
        return entity;
    }

    /**
     * 根据线路信息，线路Id,上下行类型获取单程线路信息
     * @param line
     * @param routeId
     * @param type
     * @return
     */
    private SegmentInfo getSegmentInfoList(TbBusLine line , String routeId, Integer type) {
        SegmentInfo segmentInfo = new SegmentInfo();
        segmentInfo.setLineId(line.getLineId());
        segmentInfo.setLineSerial(line.getLineSerial());
        segmentInfo.setSegmentId(line.getLineId()+"_"+type);
        if (type == 1)
        {
            segmentInfo.setFirstTime(line.getFirstTime());
            segmentInfo.setLastTime(line.getLastTime());
            segmentInfo.setStationNumber(line.getStationNumber());
        }
        else
        {
            segmentInfo.setFirstTime(line.getFirstTimeD());
            segmentInfo.setLastTime(line.getLastTimeD());
            segmentInfo.setStationNumber(line.getStationNumberD());
        }

        segmentInfo.setTicketPrice(line.getTicketPrice());

        segmentInfo.setStations(tbBusStationService.selectListByRouteId(routeId,type));
        int count = segmentInfo.getStations().size();
        if(count>0){
            segmentInfo.setStationFrom(segmentInfo.getStations().get(0).getStationName());
            segmentInfo.setStationTo(segmentInfo.getStations().get(count-1).getStationName());
        }
        return segmentInfo;
    }



}